﻿using System;
using System.Linq;
using Batman.BLL.UserModule.Extensions;
using Batman.Core;
using Batman.DLL.Todo;
using Batman.DLL.Todo.Models;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Batman.Web.Api.Todo.Controllers
{
    [ApiController]
    [Route("todo/[controller]")]
    public class TodoItemController : ControllerBase
    {
        private readonly TodoDbContext _todoDbContext;

        public TodoItemController(TodoDbContext todoDbContext)
        {
            _todoDbContext = todoDbContext;
        }

        [HttpPost]
        public async Task<ResponseBase<TodoItem>> Post(TodoItem model)
        {
            using (_todoDbContext)
            {
                model.Content = model.Content.Trim();
                model.CreateBy = Request.HttpContext.User.GetUserId();
                await _todoDbContext.TodoItem.AddAsync(model);
                await _todoDbContext.SaveChangesAsync();

                return new ResponseBase<TodoItem>(model);
            }
        }

        [HttpPut]
        [Route("Name")]
        public async Task<ResponseBase<TodoItem>> UpdateName(TodoItem model)
        {
            using (_todoDbContext)
            {
                var todoItem = _todoDbContext.TodoItem.AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
                if (todoItem == null) return new ResponseBase<TodoItem>();
                if (HttpContext.User.GetUserId() != todoItem.CreateBy) return new ResponseBase<TodoItem>(false, "无权修改");

                todoItem.Content = model.Content;

                _todoDbContext.Update(todoItem);
                await _todoDbContext.SaveChangesAsync();
                return new ResponseBase<TodoItem>(todoItem);
            }
        }

        [HttpPut]
        [Route("Top")]
        public async Task<ResponseBase> Update(TodoItem model)
        {
            using (_todoDbContext)
            {
                var todoItem = _todoDbContext.TodoItem.AsNoTracking().FirstOrDefault(t => t.Id == model.Id);
                if (todoItem == null) return new ResponseBase(false, "不存在待办");
                if (HttpContext.User.GetUserId() != todoItem.CreateBy) return new ResponseBase(false, "无权修改");

                todoItem.IsTop = model.IsTop;
                todoItem.TopAt = todoItem.IsTop ? DateTime.Now : default(DateTime?);

                _todoDbContext.Update(todoItem);
                await _todoDbContext.SaveChangesAsync();
                return new ResponseBase(todoItem);
            }
        }
    }
}
